package com.mollytask.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.mollytask.R;
import com.mollytask.bean.Message;
import com.mollytask.bean.MyUser;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * Created by freshxu on 2017/5/30.
 */

public abstract class BaseMessageFragment extends Fragment {


    private RecyclerView mRecyclerView;

    protected List<Message> mMessages = new ArrayList<>();


    private MessageAdapter mAdapter;

    protected MyUser myUser;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(getLayout(), container, false);
        myUser = BmobUser.getCurrentUser(MyUser.class);
        initRecyclerView(view);
        initData();
        init();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    public abstract int getLayout();

    public abstract void init();

    public abstract int getRecyclerViewId();


    protected void initRecyclerView(View view) {
        mRecyclerView = (RecyclerView) view.findViewById(getRecyclerViewId());
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(manager);
        mAdapter = new MessageAdapter(R.layout.item_message, mMessages);
        mRecyclerView.setAdapter(mAdapter);

    }

    private void initData() {

        BmobQuery<Message> query = new BmobQuery<>();
        query.addWhereEqualTo("mToCode", myUser.getCode());
        query.order("-createdAt");
        query.findObjects(new FindListener<Message>() {
            @Override
            public void done(List<Message> list, BmobException e) {
                if (e == null) {
                    mMessages = list;
                    if (mAdapter == null) {
                        mAdapter = new MessageAdapter(R.layout.item_message, mMessages);
                        mRecyclerView.setAdapter(mAdapter);
                    }
                    mAdapter.notifyDataSetChanged();
                }
            }
        });

    }
}
